import { Component, OnInit } from '@angular/core';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { ApiService } from 'src/app/core/api';
import { MessageService } from 'src/app/core/service/message.service';
import { FormBuilder, Validators } from '@angular/forms';
import { urlService } from './../../../core/api/url';
import { Router, ActivatedRoute } from '@angular/router';
import { DatePipe } from '@angular/common';
import { StringifyOptions } from 'querystring';
import { I18nService } from 'src/app/core/i18n/i18n.service';

@Component({
	templateUrl: './guideAdd.html',
	providers: [DatePipe],
})
export class GuideAddComponent implements OnInit {
	page: any = {
		pageNo: 1,
	};
	travelAgencyList = [];
	dateRange;
	dataList = [];
	personalityTagList = [];
	guideServiceItemList = [];
	isVisible = false;
	tableLoading = false;
	modalTitle;
	selectedRowData: any = {};
	validateForm;
	fileList = [];
	classifyList = [];
	previewImage;
	showTime = false;
	uploadUrl = urlService('dev', '上传图(唯一路口)');
	personalityTagObj: any = {};
	guideServiceItemObj: any = {};
	id;
	modal;
	imageChangedEvent;
	constructor(private i18n:I18nService ,private apiService: ApiService, private nzMessageService: NzMessageService, private message: MessageService, private fb: FormBuilder, private router: Router, private datePipe: DatePipe, private activeRouter: ActivatedRoute) {
		this.id = this.activeRouter.snapshot.queryParams['id'];
		this.i18n.get('modal').subscribe(res=>{
			this.modal = res;
		})
	}
	ngOnInit() {
		this.validateForm = this.fb.group({
			name: [null, [Validators.required]],
			travelAgencyId: [null, [Validators.required]],
			birthday: [null],
			reservationFee: [null, [Validators.required]],
			time: [[{ weekday: 'monOpenTime', timeStart: new Date('1990-01-01 09:00'), timeEnd: new Date('1990-01-01 18:00') }], [Validators.required]],
			personalityTagList: [null],
			guideServiceItemList: [null],
			brief: [null, [Validators.required]],
			header:[null, [Validators.required]],
			// cateIds:[null,[Validators.required]]
		});
		if (this.id) {
			this.apiService.post('导游详情', { id: this.id }).then((res: any) => {
				const { name, reservationFee, birthday, brief, agencyId: travelAgencyId } = res.data.travelGuideDetail;
				// const cateList = [];
				// if(res.data.agencyTravelCategoryList && res.data.agencyTravelCategoryList.length>0){
				// 	res.data.agencyTravelCategoryList.forEach(e=>{
				// 		cateList.push(e.cateId);
				// 	})
				// }
				res.data.travelGuideDetail.guideServiceItemList.forEach(item => {
					item.checked = true;
					this.guideServiceItemObj[item.name] = item.id;
				});
				res.data.travelGuideDetail.personalityTagList.forEach(item => {
					item.checked = true;
					this.personalityTagObj[item.name] = item.id;
				});
				this.fileList = res.data.travelGuideDetail.images.split(',').map(item => {
					return { url: item, status: 'done', thumbUrl: item, uid: item };
				});
				this.validateForm.patchValue({
					name,
					travelAgencyId,
					birthday,
					reservationFee,
					time: this.getTimeList(res.data.travelGuideDetail),
					personalityTagList: Object.keys(this.personalityTagObj),
					guideServiceItemList: Object.keys(this.guideServiceItemObj),
					brief,
					header:this.fileList.shift().url,
					// cateIds:cateList.length>0?cateList:null
				});
				
				console.log(res);
			});
		}
		this.message.setBreadcrumb({
			breadcrumbs: [{ name: '导游管理' }],
		});
		this.apiService.post('旅游社列表(用于选择框)', {}).then((res: any) => {
			this.travelAgencyList = res.data.list;
			this.tableLoading = false;
		});
		this.apiService.post('获取个性标签', {}).then((res: any) => {
			this.personalityTagList = res.data;
			this.tableLoading = false;
		});
		this.apiService.post('获取服务项目', {}).then((res: any) => {
			this.guideServiceItemList = res.data;
			this.tableLoading = false;
		});
		this.apiService.post('旅游分类列表', {pageNo:1,mode:'DESIGNATED',providerType:'GUIDE'}).then((res: any) => {
			this.classifyList = res.data.list;
		});
	}
	handlePreview = (file: UploadFile) => {
		this.previewImage = file.url || file.thumbUrl;
		window.open(this.previewImage);
	};
	getTimeList(data) {
		const array = [];
		const timer = new Date().getTime();
		if (data.monOpenTime) {
			array.push({ weekday: 'monOpenTime', timeStart: new Date('1990-01-01 ' + data.monOpenTime), timeEnd: new Date('1990-01-01 ' + data.monCloseTime) });
		}
		if (data.tueOpenTime) {
			array.push({ weekday: 'tueOpenTime', timeStart: new Date('1990-01-01 ' + data.tueOpenTime), timeEnd: new Date('1990-01-01 ' + data.tueCloseTime) });
		}
		if (data.wedOpenTime) {
			array.push({ weekday: 'wedOpenTime', timeStart: new Date('1990-01-01 ' + data.wedOpenTime), timeEnd: new Date('1990-01-01 ' + data.wedCloseTime) });
		}
		if (data.thuOpenTime) {
			array.push({ weekday: 'thuOpenTime', timeStart: new Date('1990-01-01 ' + data.thuOpenTime), timeEnd: new Date('1990-01-01 ' + data.thuCloseTime) });
		}
		if (data.friOpenTime) {
			array.push({ weekday: 'friOpenTime', timeStart: new Date('1990-01-01 ' + data.friOpenTime), timeEnd: new Date('1990-01-01 ' + data.friCloseTime) });
		}
		if (data.satOpenTime) {
			array.push({ weekday: 'satOpenTime', timeStart: new Date('1990-01-01 ' + data.satOpenTime), timeEnd: new Date('1990-01-01 ' + data.satCloseTime) });
		}
		if (data.sunOpenTime) {
			array.push({ weekday: 'sunOpenTime', timeStart: new Date('1990-01-01 ' + data.sunOpenTime), timeEnd: new Date('1990-01-01 ' + data.sunCloseTime) });
		}
		if (array.length < 1) {
			array.push({ weekday: 'monOpenTime', timeStart: new Date('1990-01-01 09:00'), timeEnd: new Date('1990-01-01 18:00') });
		}
		return array;
	}
	change(item) {
		console.log(item);
		if (item.type === 'success') {
			if (item.file.response) {
				if (item.file.response.status === '0') {
					this.fileList[this.fileList.length - 1].url = item.file.response.data.url;
				} else {
					item.fileList.pop();
					this.nzMessageService.warning(item.file.response.message);
				}
			}
		} else if (item.type === 'error') {
			if (item.file.response) {
				if (item.file.response.status === 403) {
					this.router.navigateByUrl('/pages/login');
				} else {
					this.nzMessageService.warning(item.file.response.message);
				}
			} else {
				this.nzMessageService.warning(this.modal.warn1);
			}
			item.fileList.pop();
		}
	}
	beforeUpload = file => {
		console.log(file);
		if (file.size > 1024 * 1024) {
			this.nzMessageService.warning(this.modal.guideWarn1);
			return false;
		} else {
			return true;
		}
	};
	addTime(i) {
		this.showTime = true;
	}
	removeTime(i) {
		this.showTime = false;
		this.validateForm.patchValue({ timeStart2: null, timeEnd2: null, timeType2: null });
	}
	personalityTagChange(e, item) {
		if (e) {
			this.personalityTagObj[item.name] = item.id;
		} else {
			delete this.personalityTagObj[item.name];
		}
		this.validateForm.controls.personalityTagList.setValue(Object.keys(this.personalityTagObj));
	}
	changePersonalityTag(model) {
		let add = '';
		const obj = {};
		model.forEach(element => {
			if (this.personalityTagObj[element]) {
				obj[element] = this.personalityTagObj[element];
			} else {
				obj[element] = 999;
				add = element;
			}
		});
		if (add) {
			this.apiService.post('创建个性标签', { name: add }).then((res: any) => {
				obj[add] = res.data.id;
				this.personalityTagObj = obj;
			});
		} else {
			this.personalityTagObj = obj;
		}
	}
	guideServiceItemChange(e, item) {
		if (e) {
			this.guideServiceItemObj[item.name] = item.id;
		} else {
			delete this.guideServiceItemObj[item.name];
		}
		this.validateForm.controls.guideServiceItemList.setValue(Object.keys(this.guideServiceItemObj));
	}
	changeGuideService(model) {
		let add = '';
		const obj = {};
		console.log(model, this.guideServiceItemObj);
		model.forEach(element => {
			if (this.guideServiceItemObj[element]) {
				obj[element] = this.guideServiceItemObj[element];
			} else {
				obj[element] = 999;
				add = element;
			}
		});
		if (add) {
			this.apiService.post('创建服务项目', { name: add }).then((res: any) => {
				obj[add] = res.data.id;
				this.guideServiceItemObj = obj;
			});
		} else {
			this.guideServiceItemObj = obj;
		}
	}
	filterOption = () => {
		return null;
	};

	submit() {
		console.log(this.validateForm.value);
		for (const v in this.validateForm.controls) {
			this.validateForm.controls[v].markAsDirty();
			this.validateForm.controls[v].updateValueAndValidity();
		}
		if (this.validateForm.valid) {
			if (this.fileList.length < 2) {
				this.nzMessageService.warning(this.modal.guideWarn2);
				return;
			}
			const { name, travelAgencyId, birthday, reservationFee, brief, time, header } = this.validateForm.value;
			const data: any = {
				name,
				travelAgencyId,
				birthday: birthday ? this.datePipe.transform(birthday, 'yyyy-MM-dd') : '',
				reservationFee,
				brief,
			};
			data.time = {};
			for (let i = 0; i < time.length; i++) {
				const element = time[i];
				if (!element.weekday || !element.timeStart || !element.timeEnd) {
					this.nzMessageService.warning(this.modal.guideWarn3);
					return;
				}
				data.time[element.weekday] = this.datePipe.transform(element.timeStart, 'HH:mm') + '-' + this.datePipe.transform(element.timeEnd, 'HH:mm');
			}
			data.personalityTagList = Object.values(this.personalityTagObj);
			data.guideServiceItemList = Object.values(this.guideServiceItemObj);
			data.images = [];
			this.fileList.forEach(e => {
				console.log(e);
				data.images.push(e.url);
			});
			data.images.unshift(header);
			if (this.id) {
				data.id = this.id;
			}
			const url = this.id ? '编辑导游' : '创建导游';
			this.apiService.post(url, data).then((res: any) => {
				this.nzMessageService.success(this.id ? this.modal.guideSuccess2 : this.modal.guideSuccess1);
				this.router.navigateByUrl('/basicSetting/guideMgmt');
			});
		}
	}
}
